<template>
  <div class="app-container">
    <el-form @submit.native.prevent :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px" :label-position="labelPosition">
      <el-form-item label="单号" prop="pzbh">
        <el-input
          v-model="queryParams.pzbh"
          placeholder="请输入单号"
          clearable
          @keyup.enter.native="enterClick"
        />
      </el-form-item>
      <el-form-item label="关联单号" prop="pzbh1">
        <el-input
          v-model="queryParams.pzbh1"
          placeholder="请输入关联单号"
          clearable
          @keyup.enter.native="enterClick"
        />
      </el-form-item>
      <el-form-item label="外部单号" prop="wbdh">
        <el-input
          v-model="queryParams.wbdh"
          placeholder="请输入外部单号"
          clearable
          @keyup.enter.native="enterClick"
        />
      </el-form-item>
      <el-form-item label="客户" prop="spkhmc">
        <el-select
            v-model="queryParams.spkhmc"
            placeholder="请输入客户"
            clearable
            @change="changeSelectClient3"
            filterable
            :loading="selectClient3Loading || loading"
        >
            <el-option
                v-for="(item, index) in client3List"
                :key="index"
                :label="item.khmc"
                :value="item.khmc"
            />
        </el-select>
      </el-form-item>
      <el-form-item label="条码" prop="sptm">
        <el-input
          v-model="queryParams.sptm"
          placeholder="请输入条码"
          clearable
          @keyup.enter.native="enterClick"
        />
      </el-form-item>
      <el-form-item label="柜号/批号" prop="spgh">
        <el-input
          v-model="queryParams.spgh"
          placeholder="请输入柜号/批号"
          clearable
          @keyup.enter.native="enterClick"
        />
      </el-form-item>
      <el-form-item label="仓库" prop="spckmc">
        <el-select
            v-model="queryParams.spckmc"
            placeholder="请选择"
            clearable
            @change="changeWarehouse"
            filterable
            :loading="selectWarehouse15Loading || loading"
        >
            <el-option
                v-for="item in warehouseList"
                :key="item.spckid"
                :label="item.spckmc"
                :value="item.spckid"
            />
        </el-select>
      </el-form-item>
      <el-form-item label="仓位" prop="ckcw">
        <el-select
            v-model="queryParams.ckcw"
            placeholder="请选择"
            clearable
            @change="changeWarehousePosition"
            filterable
            :loading="selectPosition2Loading || loading"
        >
            <el-option
                v-for="item in warehousePositionList"
                :key="item.liid"
                :label="item.ckcw"
                :value="item.liid"
            />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="shzt">
        <el-select
            v-model="queryParams.shzt"
            placeholder="请选择"
            clearable
            @change="changeWarehouseAuditState"
        >
            <el-option
                v-for="item in auditState"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
        </el-select>
      </el-form-item>
      <el-form-item label="车牌" prop="dzzy6">
        <el-input
          v-model="queryParams.dzzy6"
          placeholder="请输入车牌"
          clearable
          @keyup.enter.native="enterClick"
        />
      </el-form-item>
      <el-form-item label="入仓日期" prop="warehouseInDate">
        <el-date-picker
          v-model="warehouseInDate"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="warehouseInDateChange()">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="queryParams.jqcz" label="精确查找" true-label="1" @change="getList"></el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
     <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain size="mini" @click="handleSceneWarehouseIn" v-hasPermi="['zhcloud:hwrc:add']">入仓办单</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button  type="primary" plain size="mini" @click="handelPatchAudit"  :disabled="selection.length === 0" v-hasPermi="['zhcloud:hwrc:audit']">批量审核</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain size="mini" @click="handleExport" :disabled="selection.length === 0" v-hasPermi="['zhcloud:hwrc:export']">导出</el-button>
        </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      :data="warehouseInList"
      :show-summary="false"
      :summary-method="getSummaries"
      @selection-change="handleSelectionChange"
    >
      <af-table-column type="selection" width="60" align="center" />  
      <af-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150" fixed="left">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleOpenDetail(scope.row)"
            v-hasPermi="['zhcloud:hwrc:detail']"
          >详细</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handlePrint(scope.row)"
            v-hasPermi="['zhcloud:hwrc:print']"
          >打印</el-button>
            <el-button
            size="mini"
            type="text"
            @click="handleJumpDetail(scope.row)"
            v-hasPermi="['zhcloud:hwrc:list']"
          >跳转明细</el-button>
        </template>
      </af-table-column>
      <af-table-column prop="dzzy9" label="打印次数"  fixed="left"></af-table-column>
      <af-table-column prop="yydh" label="关联单号" ></af-table-column>
      <af-table-column prop="wbdh" label="外部单号" ></af-table-column>
      <af-table-column prop="pzbh" label="单号" ></af-table-column>
      <af-table-column prop="ssrqid" label="入仓日期" ></af-table-column>
      <af-table-column prop="khmc" label="客户" ></af-table-column>
      <af-table-column prop="spjs" label="入仓件数" ></af-table-column>
      <af-table-column prop="spsl" label="入仓重量(吨)" ></af-table-column>
      <af-table-column prop="spzs" label="物品规格" ></af-table-column>
      <af-table-column prop="dzzy6" label="车牌" ></af-table-column>
      <af-table-column prop="rsopmc" label="创建人" ></af-table-column>
      <af-table-column prop="prrq" label="创建时间" ></af-table-column>
      <af-table-column prop="shrqid" label="审核日期" ></af-table-column>
      <af-table-column prop="shrsmc" label="审核人" ></af-table-column>
      <af-table-column prop="dzbz" label="备注"  width="150" :show-overflow-tooltip="true"></af-table-column>
      <af-table-column prop="shzt" label="审核状态" ></af-table-column>
      <af-table-column prop="dzzy12" label="实际结算方" ></af-table-column>
    </el-table>
     <pagination
        v-show="total>0"
        :total="total"
        :page.sync="pageNum"
        :limit.sync="pageSize"
        @pagination="getList"
      />
  </div>

</template>

<script>
import { ListWarehouseIn, warehouseInAudit, selectPosition2} from "@/api/storage/commonGoods/warehouseIn";
import { selectClient3 } from "@/api/storage/customer"
import { selectWarehouse15 } from "@/api/storage/warehouse"
import ExportJsonExcel from 'js-export-excel'
import { NUMBER_DIDGIT, WEIGHT_DIGIT } from '@/utils/constant'
import { formatDate, calculateDays } from '@/utils'

export default {
  name: "WarehouseIn",
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      //表格加载
      loading:true,
      //客户加载
      selectClient3Loading:true,
      //仓库加载
      selectWarehouse15Loading:true,
      //仓位加载
      selectPosition2Loading: true,
      //对齐
      labelPosition: "right",
      //审核状态
      auditState:[{
        value: "未审核",
        label:"未审核"
      },{
        value: "已审核",
        label:"已审核"
      }],
      warehouseInDate:'',
      // 查询参数
      queryParams: {
        ckcw: "",
        dzzy6: "",
        jqcz: "",
        pzbh: "",
        pzbh1: "",
        rqid1: "",
        rqid2: "",
        shzt: "",
        spbh: "",
        spckmc: "",
        spgh: "",
        spkhmc: "",
        spkhmc1: "",
        sptm: "",
        ssrqid: "",
        wbdh: ""
      },
      //获取仓位参数
      selectPositionQuery:{
         spckid:""
      },
      //获取客户参数
      selectClient3Query: {
        name1:""
      },
      //仓位列表
      warehousePositionList:[],
      //批量审核数据
      selection:[],
      // 货物入仓列表
      warehouseInList: [],
      //仓库列表
      warehouseList:[],
      //客户列表
      client3List: [],
      //页数
      pageSize: 10,
      //页码
      pageNum:1,
      // 总条数
      total: 0,
    };
  },
  beforeRouteEnter(to, from, next) {
    const params = to.params
    next(vm => {   
      if(Object.keys(params).length > 0) {
        if(to.params.refresh == true) {
          vm.getList()
        }
      }
    })
  },
  created() {
    this.getWarehouse()
    this.getClient3()
    this.getList()
  },
  methods: {
     /**获取客户 */
    getClient3() {
      this.selectClient3Loading = true
      selectClient3(this.selectClient3Query).then(response => {
        this.client3List = response.data
        this.selectClient3Loading = false
      });
    },
    /**获取仓库 */
    getWarehouse() {
      this.selectWarehouse15Loading = true
      selectWarehouse15({}).then(response => {
        this.warehouseList = response.data
        this.selectWarehouse15Loading = false
      });
    },
    /**获取仓位 */
    getWarehousePosition() {
      this.selectPosition2Loading = true
      selectPosition2(this.selectPositionQuery).then(response => {
        this.warehousePositionList = response.data
        this.selectPosition2Loading = false
      });
    },
    /** 查询货物入仓列表 */
    getList() {
      this.loading = true
      ListWarehouseIn(this.queryParams, {pageNum:this.pageNum, pageSize:this.pageSize}).then(response => {
        this.warehouseInList = response.rows;
        this.total = response.total;
        this.loading = false
      });
    },

     /**入仓批量审核 */
    warehouseInAudit() {
      this.$modal.loading("数据正在审核中，请稍等...")
      warehouseInAudit(this.selection).then(response => {
        this.$modal.closeLoading()
        this.$modal.msgSuccess('审核成功！')
        this.getList()
      }).catch(()=> {
        this.$modal.closeLoading()
      })
    },

    /**选择仓库 */
    changeWarehouse(id) {
      this.selectPositionQuery.spckid = id
      this.queryParams.ckcw = ""
      this.warehousePositionList = []
      if(this.selectPositionQuery.spckid) {
        this.getWarehousePosition()
      }
      this.getList()
    },
    /**选择仓位 */
    changeWarehousePosition() {
      this.getList()
    },

    /**选择审核状态 */
    changeWarehouseAuditState() {
      this.getList()
    },
    /**选择客户 */
    changeSelectClient3() {
        this.getList()
    },

     /**选择入仓时间 */
    warehouseInDateChange() {
      this.queryParams.rqid1 = this.warehouseInDate?this.warehouseInDate[0]:""
      this.queryParams.rqid2 = this.warehouseInDate?this.warehouseInDate[1]:""
      this.getList()
    },

    /** 批量审核*/
    handelPatchAudit() {
      const nowDate = formatDate(Date.now()).split(" ")[0]
      const selection = this.selection
      for(let i in selection) {
        if(selection[i].shzt == "已审核") return this.$modal.msgWarning("已审核的单不允许再次审核！")
      }
       //如果当前时间（审核日期）小于入仓日期，则系统提示：入仓日期大于当前日期，审核失败！
       if(selection && selection.length > 0) {
        const sortSelection = selection.sort((a,b) => a.ssrqid>b.ssrqid?-1:1)
        if(calculateDays(sortSelection[0].ssrqid, nowDate) < 0) return this.$modal.msgWarning("入仓日期大于当前日期，审核失败！")
      }
      this.$modal.confirm('是否确认次操作？').then(() => {
        this.warehouseInAudit()
      }).catch(() => {});
    },

    /** 现场入仓*/
    handleSceneWarehouseIn() {
        this.$router.push({path:"/storage/commonGoods/warehouseIn/sceneWarehouseIn"})
    },

    /**详情 */
    handleOpenDetail(row) {
      this.$router.push({path:"/storage/commonGoods/warehouseIn/warehouseInDetail", query:{
        dzid:row.dzid,
      }})
    },

    /**打印 */
    handlePrint(row) {
      this.$router.push({path:'/storage/commonGoods/warehouseIn/warehouseInPrint',query:{dzid: row.dzid, shzt:row.shzt}})
    },

    /**跳转入仓总览详情 */
    handleJumpDetail(row) {
      this.$router.push({path:"/storage/commonGoods/warehouseInOverview", query:{pzbh:row.pzbh}})
    },

    /** 导出勾选数据*/
    handleExport() {
      if (this.selection.length > 0) {
        let option = {}
        option.fileName = '货物入仓勾选数据'
        option.datas = [
          {
            sheetData: this.selection,//数据
            sheetName: 'sheet',
            //表头数据对应的sheetData数据
            sheetFilter: ['dzzy9', 'yydh', 'wbdh', 'pzbh', 'ssrqid', 'khmc', 'spjs', 'spsl', 'spzs', 'dzzy6', 'rsopmc', 'prrq', 'shrqid', 'shrsmc', 'dzbz', 'shzt', 'dzzy12'],
            sheetHeader: [
              //表头数据
              '打印次数', '关联单号', '外部单号', '单号', '入仓日期', '客户','入仓件数', '入仓重量(吨)','物品规格', '车牌','创建人','创建时间','审核日期','审核人','备注','审核状态', '实际结算方'],
          }
        ]
        let excel = ExportJsonExcel(option)
        excel.saveExcel()
      } else {
        this.$modal.msgError('请勾选数据');
      }
    },

    //合计
    getSummaries({ columns, data }) {
      const sums = []
      columns.forEach((column, index) => {
        if(index === 0) {
          sums[index] = "合计"
			    return
        }
        if ((column.property === "spjs" || column.property === "spsl")) {
          const values = data.map((item) => {
            return parseFloat(this.delcommafy(item[column.property]))
          });
          sums[index] = values.reduce((prev, curr) => {
            if(!prev) prev = 0
            if(!curr) curr = 0
            if(column.property === "spsl") {
              return parseFloat((prev + curr).toFixed(WEIGHT_DIGIT))
            }
            if(column.property === "spjs") {
              return parseFloat((prev + curr).toFixed(NUMBER_DIDGIT))
            }
          }, 0);
        }
      })
      return sums
    },

     // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection
    },
    /**enter键触发 */
    enterClick(e) {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.reset()
      this.getWarehouse()
      this.getClient3()
      this.getList()
    },
    reset() {
      Object.assign(this.$data, this.$options.data())
    },
  }
};
</script>
